<script lang="ts" setup>
import {ref} from 'vue'
import { Plus } from '@element-plus/icons-vue'
import {uploadAvatarAPI} from '@/apis/user.js'
import {useUserStore} from '@/stores/user'
import {ElMessage, UploadInstance, UploadProps, UploadUserFile} from 'element-plus'


const imgFile=defineModel("file")

//缩略图列表
const fileList = ref<UploadUserFile[]>([])
const FILES=ref()
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log("移除了一张图片")
  imgFile.value.pop(uploadFile)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

const handleChange: UploadProps['onChange']=(UploadFile, UploadFiles) => {
  FILES.value=UploadFiles
  let flag=true
  if(UploadFile.size / 1024 / 1024 > 4){
    ElMessage.error('图片大小不能超过 4MB!');
    handleRemove(UploadFile,UploadFiles)
    flag=false
    return
  }

  imgFile.value.forEach((item,index)=>{
    if(item.uid===UploadFile.uid){
      flag=false
      return
    }
  })
  if(flag){
    imgFile.value.push(UploadFile)
    console.log("添加了一张图片,大小",UploadFile.size,UploadFile.raw,imgFile.value.length)
  }
}

const handleExceed=()=>{
  ElMessage({
    type:'error',
    message:"最多上传6张图片"
  })
}

// 上传前的验证
const beforeImgUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 4;
  if (!isJpgOrPng) {
    ElMessage.error('图片只能是 JPG 或 PNG 格式!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 4MB!');
    return false;
  }
  return true;
};


// 上传图片到OSS
const uploadImg = async (options) => {
  return true
};

//设置为手动上传
const uploadRef = ref<UploadInstance>()

const submitUpload = () => {
  uploadRef.value!.submit()
}

const clearFiles=()=>{
  uploadRef.value.clearFiles()
  imgFile.value=[]
}

function getImageFile() {
  return FILES
}

// 暴露方法给父组件
defineExpose({ submitUpload ,clearFiles,getImageFile})

</script>

<template>
  <el-upload
      ref="uploadRef"
      v-model:file-list="imgFile"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-change="handleChange"
      :on-exceed="handleExceed"
      :auto-upload="false"
      :multiple="true"
      :limit=6

      :before-upload="beforeImgUpload"
      :http-request="uploadImg"

  >
    <el-icon><Plus /></el-icon>

    <template #tip>

    </template>

  </el-upload>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>


